import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/ShowDialog.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'package:platform/platform.dart';
class AddFamiliarCars extends StatefulWidget {
  const AddFamiliarCars({super.key});

  @override
  State<AddFamiliarCars> createState() => _AddFamiliarCarsState();
}

class _AddFamiliarCarsState extends State<AddFamiliarCars> {
  List dataList=[];


  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();

  @override
  void initState() {
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });

    getMyDriversAction("2",1);

    super.initState();
  }

  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        showCallPhoneFirstDialog(context);
        // 权限被拒绝，但用户可以再次授权
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }

  void getMyDriversAction(String shipperId,int current) async {
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.get<String>(MyServiceUrl.header+'api/goods/shpr/familiardrv/page?shipperId=$shipperId&current=$current')
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          dataList  = jsonMap['data'];
        } else {}
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });
  }


  void searchDriverAction(String drvPhoneNum,String vehicleNum) async {
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] =token;
          return handler.next(options);
        }
    ));
    dio.get<String>(MyServiceUrl.header+"api/user/shpr/familiardrv/getDrv?shipperId=$drvPhoneNum&current=$vehicleNum")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          dataList  = jsonMap['data'];
        } else {}
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("添加熟车",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body: Column(
        children: [
          BrnSearchText(
            focusNode: focusNode,
            controller: textController,
            searchController: scontroller..isActionShow = false,
            outSideColor:MyColors.backgreyColor,
            innerColor:Colors.white,
            borderRadius:BorderRadius.all(const Radius.circular(10.0)),
            hintText:"输入司机手机号码/车牌号",
            onTextClear: () {
              debugPrint('sss');
              return false;
            },
            autoFocus: true,
            onActionTap: () {
              scontroller.isClearShow = false;
              scontroller.isActionShow = false;
              focusNode.unfocus();

            },
            onTextCommit: (text) {

            },
            onTextChange: (text) {
              if (text.contains(RegExp(r'[a-zA-Z]')) && text.length > 0) {
                searchDriverAction(text,"");
              } else {
                searchDriverAction("",text);
              }

            },
          ),
      Container(
        margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w,),
        height: screenSize.height-180.h,
        child:  ListView.builder(
            shrinkWrap:false,
            itemCount:dataList.length,
            itemBuilder: (BuildContext context, int index) {
              return Container(
                decoration: BoxDecoration(
                    color:Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w,),
                padding: EdgeInsets.all(15.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Image.asset("lib/Images/login/微信登录.png",width: 36.w,height: 36.h,),
                            SizedBox(width: 8.w,),
                            Text(dataList[index]['driverName'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 16.sp),),
                          ],
                        ),
                        if(dataList[index]['personalStatus']==2&&dataList[index]['driverLinsenseStatus']==2&&dataList[index]['vehicleDrivingLisenseStatus']==2
                            &&(dataList[index]['qualificationCertificateStatus']!=2||dataList[index]['roadTransportCertificateStatus']!=2))
                          BrnTagCustom.buildBorderTag(
                            tagText: '三证齐全',
                            textColor: MyColors.themeColor,
                            borderColor: MyColors.themeColor,
                            borderWidth: 1.w,
                            fontSize: 11.sp,
                          ),
                        if(dataList[index]['personalStatus']==2&&dataList[index]['driverLinsenseStatus']==2&&dataList[index]['vehicleDrivingLisenseStatus']==2
                            &&dataList[index]['qualificationCertificateStatus']==2&&dataList[index]['roadTransportCertificateStatus']==2)
                          BrnTagCustom.buildBorderTag(
                            tagText: '五证齐全',
                            textColor: MyColors.themeColor,
                            borderColor: MyColors.themeColor,
                            borderWidth: 1.w,
                            fontSize: 11.sp,
                          ),
                      ],
                    ),
                    SizedBox(height: 8.h,),
                    Text(dataList[index]['vehicleNum'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 16.sp)),
                    SizedBox(height:4.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Text(dataList[index]['vehicleLength']+"米"+"丨"+dataList[index]['vehicleType']+"  "+"4.5吨",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),)
                          ],
                        ),
                        RichText(
                          text: TextSpan(
                            text: '好评率 ', // 第一部分文本
                            style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),
                            children: [
                              TextSpan(
                                text: dataList[index]['driverReview']!=null?'100%':"暂无评价", // 第二部分文本
                                style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    Divider(
                      height: 16.h,
                      color: MyColors.backgreyColor,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                      Text("该用户暂不是你的熟车",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),),
                        BrnSmallMainButton(
                          title: '添加到我的熟车',
                          textColor: Colors.white,
                          bgColor: MyColors.themeColor,
                          width: 109.w,
                          onTap: () {
                            BrnToast.show('录需求信息', context);
                          },
                        )
                      ],
                    )
                  ],
                ),
              );
            }),
      ),
        ],
      ),
    );
  }
}
